<template>
    <div class="form-page">
        <el-form
            ref="form"
            :model="form"
            :rules="formRules"
            :inline="true"
            label-width="8em"
            class="data-form"
        >
            <div class="form-item">
                <div class="title">基础信息</div>
                <div class="yx-start al-start data">
                    <el-form-item prop="name" label="姓名（昵称）">
                        <el-input v-model="form.name"></el-input>
                    </el-form-item>
                    <div class="mobile-item">
                        <el-form-item prop="mobile" label="手机号">
                            <el-input v-model="form.mobile" :disabled="edit">
                            </el-input>
<!--                            <span-->
<!--                                class="show-pwd"-->
<!--                                @click="showFullMobile = !showFullMobile"-->
<!--                            >-->
<!--                                <svg-icon-->
<!--                                    :icon-class="-->
<!--                                        showFullMobile ? 'eye-open' : 'eye'-->
<!--                                    "-->
<!--                                />-->
<!--                            </span>-->
                        </el-form-item>
                    </div>
                    <el-form-item prop="sex" label="性别"
                        ><div>
                            <el-radio-group v-model="form.sex">
                                <el-radio label="unknown">不设置</el-radio>
                                <el-radio label="boy">男</el-radio>
                                <el-radio label="girl">女</el-radio>
                            </el-radio-group>
                        </div>
                    </el-form-item>
                    <el-form-item prop="positionIds" label="职位">
                        <el-cascader
                            ref="positionRef"
                            v-model="form.positionIds"
                            v-loading="flag.positionListFlag"
                            :options="positionList"
                            placeholder="请输入关键词"
                            :show-all-levels="false"
                            clearable
                            filterable
                            :before-filter="searchPosition"
                            :props="{
                                value: 'id',
                                label: 'name',
                                emitPath: false,
                                disabled: 'edit',
                                checkStrictly: true,
                                multiple: true
                            }"
                        >
                        </el-cascader>
                    </el-form-item>
                    <el-form-item prop="roleIds" label="菜单角色">
                        <el-select
                            v-model="form.roleIds"
                            v-loading="flag.searchRolesFlag"
                            multiple
                            filterable
                            remote
                            reserve-keyword
                            placeholder="请输入关键词"
                            :remote-method="searchRoles"
                        >
                            <el-option
                                v-for="item in rolesList"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="header" label="头像" class="header">
                        <el-upload
                            class="avatar-uploader"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            :show-file-list="false"
                            accept=".jpg,.png,.jpeg"
                            :auto-upload="false"
                            :on-change="headerChange"
                        >
                            <img
                                v-if="base64Header || form.header"
                                :src="base64Header || coverImage(form.header)"
                                class="avatar"
                            />
                            <i
                                v-else
                                class="el-icon-plus avatar-uploader-icon"
                            ></i>
                        </el-upload>
                    </el-form-item>
                </div>
            </div>
            <div v-if="addAction" class="form-item xy-start al-str">
                <div class="title">登录信息</div>
                <div class="yx-start al-start data">
                    <el-form-item prop="username" label="用户名1">
                        <el-input v-model="form.username"></el-input>
                    </el-form-item>
                    <el-form-item prop="password" label="密码">
                        <el-input
                            v-model="form.password"
                            type="password"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="checkPass" label="确认密码">
                        <el-input
                            v-model="form.checkPass"
                            type="password"
                        ></el-input>
                    </el-form-item>
                </div>
            </div>

            <div class="form-item xy-start al-str">
                <div class="title">机构设置</div>
                <div class="yx-start al-start data">
                    <el-form-item prop="groupId" label="选择机构">
                        <el-cascader
                            ref="groupRef"
                            v-model="form.groupId"
                            v-loading="flag.groupListFlag"
                            :options="groupList"
                            placeholder="请输入关键词"
                            :show-all-levels="false"
                            clearable
                            filterable
                            :before-filter="searchGroupList"
                            :props="{
                                value: 'id',
                                label: 'name',
                                emitPath: false,
                                disabled: 'edit',
                                checkStrictly: true
                            }"
                        >
                        </el-cascader>
                    </el-form-item>
                </div>
            </div>
        </el-form>
        <div ref="submitDiv" class="form-item xy-center from-operation">
            <el-button
                type="primary"
                icon="el-icon-folder"
                :loading="submitFlag"
                @click="save"
                >保存</el-button
            >
            <el-button
                type="warning"
                icon="el-icon-delete-solid"
                :loading="submitFlag"
                @click="clickCancel('admin-list?refresh=false')"
                >取消</el-button
            >
        </div>
    </div>
</template>

<script>
import { FormPage, objSign } from "@/layout/mixin/iVue.js";
import { mapState } from "vuex";
import {
    fetchPositionList,
    fetchRoleList,
    checkMobileExits,
    checkUsernameExits,
    getGroupList
} from "@/api/user.js";
import { isMobile } from "@/utils/validate.js";
import { ossUpload } from "@/utils/file.js";
import { treeList2Tree, beanCopy } from "@/utils/index.js";
import AriaUtils from "element-ui/src/utils/aria-utils";
import { get, put, post } from "@/api/request";
const { keys: KeyCode } = AriaUtils;
export default {
    name: "MemberAdd",
    components: {},
    mixins: [FormPage],
    data() {
        return {
            form: {
                id: null,
                name: null,
                mobile: null,
                sex: null,
                header: null,
                positionIds: null,
                username: null,
                password: null,
                checkPass: null,
                groupId: null
            },
            base64Header: null,
            positionList: null,
            groupList : null,
            parentPositionList: null,
            rolesList: null,
            parents: null,
            parent: {
                positionId: null
            },
            formRules: {
                name: [
                    {
                        required: true,
                        message: "请输入姓名",
                        trigger: "blur"
                    },
                    {
                        min: 2,
                        max: 10,
                        message: "长度在 2 到 10 个字符",
                        trigger: "blur"
                    }
                ],
                groupId: [
                    {
                        required: true,
                        message: "请选择机构",
                        trigger: "change"
                    }
                ],
                username: [
                    {
                        required: true,
                        message: "请输入登录用户名",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (!this.addAction) {
                                callback();
                            }
                            if (value) {
                                checkUsernameExits({
                                    username: value,
                                    userType: "groupAdmin"
                                }).then(res => {
                                    if (res) {
                                        callback(new Error("用户名已经存在"));
                                    } else {
                                        callback();
                                    }
                                });
                            }
                        },
                        trigger: "blur"
                    }
                ],
                password: [
                    {
                        required: true,
                        message: "请输入密码",
                        trigger: "blur"
                    },
                    {
                        min: 6,
                        max: 20,
                        message: "长度在 6 到 20 个字符",
                        trigger: "blur"
                    }
                ],
                checkPass: [
                    {
                        required: true,
                        message: "请再次输入密码",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (value !== this.form.password) {
                                callback(new Error("两次输入密码不一致!"));
                            } else {
                                callback();
                            }
                        },
                        trigger: "blur"
                    }
                ],
                mobile: [
                    {
                        required: true,
                        message: "请输入手机号",
                        trigger: "blur"
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (!this.addAction) {
                                callback();
                            }
                            if (value) {
                                if (isMobile(value)) {
                                    checkMobileExits({
                                        mobile: value,
                                        userType: "groupAdmin"
                                    }).then(res => {
                                        if (res) {
                                            callback(
                                                new Error("手机号已被使用")
                                            );
                                        } else {
                                            callback();
                                        }
                                    });
                                } else {
                                    callback(new Error("请输入正确的手机号"));
                                }
                            }
                        },
                        trigger: "blur"
                    }
                ]
            },
            flag: {
                positionListFlag: false,
                groupListFlag: false,
                searchRolesFlag: false,
                parentFlag: false
            },
            fullMobile: "",
            showFullMobile: false
        };
    },
    computed: {
        ...mapState({}),
        haveEditRole() {
            return true;
        }
    },
    watch: {
        // "parent.positionId"() {
        //     this.searchParent();
        // },
        // showFullMobile(showFullMobile) {
        //     if (showFullMobile) {
        //         this.form.mobile = this.fullMobile;
        //     } else {
        //         this.form.mobile = this.safeMobile(this.fullMobile);
        //     }
        // }
    },
    mounted() {
        this.el();
    },
    methods: {
        async loadData(id) {
            return Promise.all([
                this.loadUserOld(id),
                this.searchGroupList()
            ]).catch(e => {
                this.$message.error("数据加载失败，请稍后在试");
            });
        },
        el() {
            const v = (ref, call) => event => {
                switch (event.keyCode) {
                case KeyCode.enter:
                    call();
                    break;
                case KeyCode.down:
                    ref.toggleDropDownVisible(true);
                    ref.focusFirstNode();
                    event.preventDefault();
                    break;
                case KeyCode.esc:
                case KeyCode.tab:
                    ref.toggleDropDownVisible(false);
                    break;
                }
            };
            this.$refs.groupRef.handleKeyDown = v(
                this.$refs.groupRef,
                this.searchGroupList
            );
            // this.$refs.parentRef.handleKeyDown = v(
            //     this.$refs.parentRef,
            //     this.searchParent
            // );
        },
        async loadUserOld(id) {
            if (!id) return;
            return get(`/user/cu/member/detail`,{id:id}).then(result => {
                this.fullMobile = result.mobile;
                result.mobile = this.safeMobile(this.fullMobile);
                beanCopy(result, this.form, false);
            });
        },
        searchGroupList(query) {
            return this.flagPromise(
                getGroupList({
                    name: query,
                    size: 100
                }).then(data => {
                    // this.parentPositionList = treeList2Tree(data);
                    this.groupList = data
                }),
                "groupListFlag"
            );
        },
        searchPosition(query) {
            return this.flagPromise(
                fetchPositionList({
                    name: query,
                    size: 100
                }).then(data => {
                    if (data.length === 0 && query) {
                        this.searchPosition();
                    } else {
                        this.positionList = treeList2Tree(data);
                    }
                }),
                "positionListFlag"
            );
        },
        searchRoles(query) {
            return this.flagPromise(
                fetchRoleList({
                    name: query,
                    size: 100
                }).then(data => {
                    this.rolesList = data;
                }),
                "searchRolesFlag"
            );
        },
        // searchParent(query) {
        //     if (!this.parent.positionId) {
        //         return;
        //     }
        //     return this.flagPromise(
        //         fetchAdminUserByPositionId({
        //             id: this.parent.positionId,
        //             name: query,
        //             size: 100
        //         }).then(data => {
        //             this.parents = treeList2Tree(data);
        //         }),
        //         "parentFlag"
        //     );
        // },
        save() {
            if (this.addAction) {
                this.clickSave(
                    "/user/cu/admin/user/edit/groupAdmin/add",
                    this.form,
                    false,
                    "admin-list?refresh=true"
                );
            } else {
                this.clickSave(
                    "/user/cu/admin/user/edit/groupAdmin/update",
                    this.form,
                    true,
                    "admin-list?refresh=true"
                );
            }
        },

        thisObjSing(data) {
            return objSign({
                ...data,
                mobile: null
            });
        },
        headerChange(file, fileList) {
            if (fileList.length > 1) {
                fileList.splice(0, 1);
            }
            const elFile = fileList[0];
            file = fileList[0].raw;
            let imgReaderl = new FileReader();
            imgReaderl.onload = evt => {
                this.base64Header = evt.target.result;
            };
            imgReaderl.readAsDataURL(file);
            ossUpload("cdn", file.name, file, p => {
                elFile.percentage = p * 100;
                elFile.status = "uploading";
            }).then(result => {
                this.form.header = result;
                elFile.status = "done";
            });
        }
    }
};
</script>
<style lang="scss" scoped>
.mobile-item {
    position: relative;
    .show-pwd {
        position: absolute;
        right: 12px;
        color: #666;
    }
}
</style>

<style lang="css">
.header .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.header .avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.header .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 4.58rem;
    height: 4.58rem;
    line-height: 4.58rem;
    text-align: center;
}
.header .avatar {
    width: 4.58rem;
    height: 4.58rem;
    display: block;
}
</style>
